from Selenium2Library.keywords.keywordgroup import KeywordGroup
from Selenium2Library.locators import ElementFinder
from operator import itemgetter

import time


class _BreezeAccountSummaryKeywords(KeywordGroup):
    """Library for Breeze See Account Summary Keywords purposes.
    
    This library is used in Breeze projects.
    """
    def __init__(self):
        """Does nothing. init only"""
        print '_BreezeAccountSummaryKeywords.__init__'
        
    def read_bmw_accounts(self):
        """Read BMW Accounts list for comparing with Accounts in Ibanking.
        
        See `Read Ibnk Accounts`
        
        "See" list comparing.

        return all account type include CASA CARD LOAN..
        """
        return self._run('read_bmw_accounts')

    def _read_bmw_accounts_hk(self):
        ''' Return a list of all accounts, cards and loans from BMW.
        '''
        names = self._element_find("//div[@id='main']/div/dl/dd/a/span[1]", False, False)
        numbers = self._element_find("//div[@id='main']/div/dl/dd/a/span[2]", False, False)
        amounts = self._element_find("//div[@id='main']/div/dl/dd/a/span[3]", False, False)
        
        accounts = []
        for i in xrange(len(names)):  # TODO
            accounts.append([names[i].text,
                             numbers[i].text.split(' ')[0],
                             amounts[i].text[:3],
                             amounts[i].text[3:]])
        self._info(len(accounts))
        return accounts

    def _read_bmw_accounts_sg(self):
        ''' Return a list of all accounts, cards and loans from BMW.
        '''
        names = self._element_find("//div[@class='ember-view']/table[1][@class='width-type-8 l-r']/tbody/tr/td[1]/a/p[1]", False, False)
        numbers = self._element_find("//div[@class='ember-view']/table[1][@class='width-type-8 l-r']/tbody/tr/td[1]/a/p[2]", False, False)
        amounts = self._element_find("//div[@class='ember-view']/table[1][@class='width-type-8 l-r']/tbody/tr/td[2]/a", False, False)
        
        accounts = []
        for i in xrange(len(names)):  # TODO
            accounts.append([names[i].text,
                             numbers[i].text[-4:].split(' ')[0],
                             amounts[i].text[:3],
                             amounts[i].text[3:].strip()])
        self._info(len(accounts))
        return accounts

    def _read_bmw_accounts_pk(self):
        names = self._element_find("//div[@id='main']/div/dl/dd/a/span[1]", False, False)
        numbers = self._element_find("//div[@id='main']/div/dl/dd/a/span[2]", False, False)
        amounts = self._element_find("//div[@id='main']/div/dl/dd/a/span[3]", False, False)
        
        accounts = []
        for i in xrange(len(names)):  # TODO
            accounts.append([names[i].text,
                            numbers[i].text,
                            amounts[i].text[:3],
                            amounts[i].text[3:]])
        self._info(len(accounts))
        return accounts

    def _read_bmw_accounts_in(self):

        """Read BMW Accounts list for BMW IN.

        return all account type include CASA CARD LOAN..
        """
        acnts = self._element_find("//*/tbody/tr", False, False)
        
        #self._info(len(acnts))

        self._info(len(acnts))

        accounts = []
        ''' get each account information from i have and I owe
            include account name,account number,amount.'''
        
        for row in acnts:  
            names = row.find_elements_by_xpath("./td[1]/a/div/p[1]")
            numbers = row.find_elements_by_xpath("./td[1]/a/div/p[2]")

            amounts = row.find_elements_by_xpath("./td[2]/a")
            accounts.append([names[0].text,
                            numbers[0].text,
                            amounts[0].text[:3],
                            amounts[0].text[3:]])
                         


        self._info(len(accounts))
        accounts.sort()
        return accounts

    def _read_bmw_accounts_id(self):
        '''For BMW ID, please refer to BMW PK if not work here
        '''
        names = self._element_find("//table[@id='table-i-have']/tbody/tr/td/a/p[1]", False, False)
        numbers = self._element_find("//table[@id='table-i-have']/tbody/tr/td/a/p[2]", False, False)
        amounts = self._element_find("//table[@id='table-i-have']/tbody/tr/td[2]/a", False, False)
        cardNames = self._element_find("//table[@id='table-i-owe']/tbody/tr/td/a/p[1]", False, False)
        cardNumbers = self._element_find("//table[@id='table-i-owe']/tbody/tr/td/a/p[2]", False, False)
        cardAmounts = self._element_find("//table[@id='table-i-owe']/tbody/tr/td[2]/a", False, False)
        
        accounts = []
        '''for i in xrange(len(cardNames)):  # TODO
            accounts.append([cardNames[i].text,
                            cardNumbers[i].text,
                            cardAmounts[i].text[:3],
                            cardAmounts[i].text[3:]])
                            '''
        for i in xrange(len(names)):  # TODO
            accounts.append([names[i].text,
                            numbers[i].text,
                            amounts[i].text[:3],
                            amounts[i].text[3:]])
        
        self._info(len(accounts))
        accounts.sort()        
        return accounts
    
    def read_ibnk_accounts(self):
        """Read iBanking Accounts list for comparing with Accounts in BMW.
        
        See `Read BMW Accounts`
        
        "See" list comparing.

        return all account type include CASA CARD LOAN..
        """
        return self._run('read_ibnk_accounts')

    def _read_ibnk_accounts_hk(self):
        ''' Return a list of all accounts, cards and loans from iBanking.
        '''
        rows = self._element_find("//table[@class='tbl_listing']/tbody/tr[@class='tbl_listing_row_even' or @class='tbl_listing_row_odd']", False, False)
        
        accounts = []
        for r in rows:  # TODO
            name = r.find_elements_by_xpath("./td[2]/a")
            number = r.find_elements_by_xpath("./td[3]")
            currencie = r.find_elements_by_xpath("./td[4]")
            curr_bal = r.find_elements_by_xpath("./td[5]")
            ava_bal = r.find_elements_by_xpath("./td[7]")
            self._info('%s> %s>' % (ava_bal[0].text[:-3], curr_bal[0].text[:-3]))
            if not ava_bal[0].text[:-3].strip() == '':
                balance = ava_bal[0].text[:-3].strip()
            else:
                balance = curr_bal[0].text[:-3].strip()
            accounts.append([name[0].text,
                             number[0].text,
                             currencie[0].text.strip(),
                             balance])
        self._info(len(accounts))
        return accounts
         
    def _read_ibnk_accounts_pk(self):
        ''' Return a list of all accounts, cards and loans from iBanking.
        '''
        rows = self._element_find("//table[@class='tbl_listing']", False, False)

        accountlist = []
        cardlist = []
        loanlist = []
        accounts = []
        
        for r in rows:  # TODO
            if r.find_elements_by_xpath("./tbody/tr[1]/th[2]")[0].text == 'Accounts':
                accountlist = r.find_elements_by_xpath("./tbody/tr[@class='tbl_listing_bottom']")
            if r.find_elements_by_xpath("./tbody/tr[1]/th[2]")[0].text == 'Cards':
                cardlist = r.find_elements_by_xpath("./tbody/tr[position()>1 and position()<last()]")
            if r.find_elements_by_xpath("./tbody/tr[1]/th[2]")[0].text == 'Loans & Saadiq Finance':
                loanlist = r.find_elements_by_xpath("./tbody/tr[position()>1 and position()<last()-1]")
        
        for r in accountlist:  # get accounts list
            name = r.find_elements_by_xpath("./td[2]/a")
            number = r.find_elements_by_xpath("./td[3]/a")
            currencie = r.find_elements_by_xpath("./td[4]")
            curr_bal = r.find_elements_by_xpath("./td[7]")
            ava_bal = r.find_elements_by_xpath("./td[5]")
            if not curr_bal[0].text[:-3].strip() == '':
                balance = curr_bal[0].text[:-3].strip()
            else:
                balance = ava_bal[0].text[:-3].strip()
            accounts.append([name[0].text,
                             number[0].text,
                             currencie[0].text.strip(),
                             balance])
        for r2 in cardlist:  # get cards list
            name = r2.find_elements_by_xpath("./td[2]/a")
            number = r2.find_elements_by_xpath("./td[3]/a")
            currencie = r2.find_elements_by_xpath("./td[4]")
            balance = r2.find_elements_by_xpath("./td[5]")[0].text[4:-3]
            accounts.append([name[0].text,
                            number[0].text,
                            currencie[0].text.strip(),
                            balance])
        for r3 in loanlist:  # get loans list
            name = r3.find_elements_by_xpath("./td[2]/a")
            number = r3.find_elements_by_xpath("./td[3]/a")
            currencie = r3.find_elements_by_xpath("./td[4]")[0].text[:3]
            balance = r3.find_elements_by_xpath("./td[4]")[0].text[4:-3]
            accounts.append([name[0].text,
                            number[0].text,
                            currencie,
                            balance])
        self._info(len(accounts))
        return accounts

    def _read_ibnk_accounts_in(self):
        ''' Return a list of all accounts, cards and loans from iBanking.
        '''
        self.click_element("//div[@id='parentMenuHeadLink']/a/table/tbody/tr/td")
        self.wait_until_page_contains("Account")

        rows = self._element_find("//table[@class='tbl_listing']/tbody/tr[@class='tbl_listing_row_even' or @class='tbl_listing_row_odd']", False, False)

        accounts = []
        curr_bal = None
        name_attribute = ''

        ''' ---following loop means ---

            get each account's name,account number,currency current balance from iBanking.

            in ibanking current balance position is different between CASA and other product

            so we use name_attribute to know the item is CASA or not
        '''
        for r in rows:  # TODO
            name = r.find_element_by_xpath("./td[2]/a")
            name_attribute = name.get_attribute("href")   #add get_attribute to identified account,card and loan,bcos balance have different position
            # self._info("name_attribute"+name_attribute)
            number = r.find_element_by_xpath("./td[3]")
            currency = r.find_element_by_xpath("./td[4]")
           # ava_bal = r.find_elements_by_xpath("./td[5]")
            if "account" in name_attribute:                     #add attribute check here
                curr_bal = r.find_element_by_xpath("./td[7]")
            else:
                curr_bal = r.find_element_by_xpath("./td[5]")

            accounts.append([name.text,
                             number.text,
                             currency.text.strip(),
                             curr_bal.text[:-3].strip()])
        self._info(len(accounts))
        accounts.sort()
        return accounts

    def _read_ibnk_accounts_id(self):
        #select to links frame for clicking "Accounts" hyperlink to see Accounts list
        self.select_links_frame_ibanking()
        self.wait_until_page_contains("Accounts")
        self.current_frame_contains("Accounts")
        
        element = self._element_find("//a[@id='nav_ML4']", True, False)
        self._info(element)
        element.click()
        self.select_top_frame_ibanking()
        self.wait_until_page_contains("Please click on \"Account Number\" to view details.")
        
        rows = self._element_find("//*[@id='acclist']/tbody/tr", False, False)
        self._info(rows)
        
        accounts = []
        
        #accounts records
        for r in rows: #TODO
            type = r.find_elements_by_xpath("./td[1]")
            number = r.find_elements_by_xpath("./td[2]")
            avail = r.find_elements_by_xpath("./td[3]")
            ledger = r.find_elements_by_xpath("./td[4]")
            self._info('%s> %s> %s> %s>' % (type[0].text, number[0].text, avail[0].text, ledger[0].text))
            accounts.append([type[0].text,
                             number[0].text.replace("-", ""),
                             ledger[0].text.split(' ')[1],
                             ledger[0].text.split(' ')[2]])
        self._info(len(accounts))
        
        #credit cards records
        '''self.select_links_frame_ibanking()
        element = self._element_find("//*[@id='nav_ML300']", True, False)
        self._info(element)
        element.click()
        self.select_top_frame_ibanking()
        self.wait_until_page_contains("Credit Cards")
        
        rows2 = self._element_find("//tr[@class='table_row_white']", False, False)
        for r2 in rows2: #TODO
            type = r2.find_elements_by_xpath("./td[1]")
            number = r2.find_elements_by_xpath("./td[2]")
            bonus = r2.find_elements_by_xpath("./td[3]")

            self._info('%s> %s> %s>' % (type[0].text, number[0].text, bonus[0].text))
            #balance = r2.find_elements_by_xpath("./td[5]")[0].text[4:-3]
            accounts.append([type[0].text,
                            number[0].text,
                            bonus[0].text.strip()])
        self._info(len(accounts))
        '''
        #do not implement "Loan" part as no data when writing script.
        accounts.sort()
        return accounts
        
    def _read_ibnk_accounts_sg(self):
        ''' Return a list of all accounts, cards and loans from iBanking.
        '''
        rows = self._element_find("//table[@class='tbl_listing']/tbody/tr[@class='tbl_listing_row_even' or @class='tbl_listing_row_odd']", False, False)
        
        accounts = []
        for r in rows:  # TODO
            name = r.find_elements_by_xpath("./td[2]/a")
            number = r.find_elements_by_xpath("./td[3]")
            currency = r.find_elements_by_xpath("./td[4]")
           # ava_bal = r.find_elements_by_xpath("./td[5]")
            curr_bal = r.find_elements_by_xpath("./td[7]")
            accounts.append([name[0].text,
                             number[0].text.split(' ')[0][6:],
                             currency[0].text.strip(),
                             curr_bal[0].text[:-3].strip()])
        self._info(len(accounts))
        return accounts

    def read_ibnk_accounts_information(self):
        """Read iBanking Accounts information for each account in BMW.
        """
        return self._run('read_ibnk_accounts_information')
    
    def _read_ibnk_accounts_information_in(self):
        '''step 1:get all account'''
        account_ls = self._read_ibnk_accounts_in()

        account_information = []

        '''step 2:get each account information and append them in return list'''
        for i in xrange(len(account_ls)):

            #self._info(account_ls[i][0])
            
            account_information = self.read_ibnk_Single_accounts_information_in(account_ls[i][0])

            account_info_all.append(account_information)
            
            self._info(len(account_info_all))
            
            
        return account_info_all
    
    def _read_ibnk_accounts_information_id(self):

        account_ls = self._read_ibnk_accounts_id()

        account_information = []
        account_info_all = []
        ''' Return a list of all accounts information, cards and loans from iBanking.
        '''
        #self.click_element("//div[@id='parentMenuHeadLink']/a/table/tbody/tr/td")

        #self.wait_until_page_contains("Account")

        for i in xrange(len(account_ls)):

            self._info(account_ls[i][0])

            account_information = self.read_ibnk_Single_accounts_information_in(account_ls[i][0])

            account_info_all.append(account_information)
            
            self._info(len(account_info_all))
            
            
        return account_info_all

    def read_ibnk_Single_accounts_information_in(self,account_name,account_type):

        ''' get CASA,CARD,LOAN'S detail information by give account name and account_type

            param: account_name, account_type
        '''
        account_information = []

        self.click_element("//div[@id='parentMenuHeadLink']/a/table/tbody/tr/td")

        self.wait_until_page_contains("Account")

        ''' step1: click required account '''
        self.click_link(account_name)
        
        self.wait_until_page_contains("Transaction History")

        self.click_element("id=tab_1")
        
        self.wait_until_page_contains_element("//table[@class='tbl_listing']")

        ''' step2: get all items for selected account  '''
        account_info = self._element_find("//table[@class='tbl_listing']/tbody/tr[@class='tbl_form_row_even' or @class='tbl_form_row_odd']", False, False)

        self._info(len(account_info))

        ''' step3: map the item in ibanking to the item displayed in BMW'''
        for r in account_info:  # TODO

            '''get drop down list for the first item'''
            content_ls = r.find_elements_by_xpath(".//td[3]/select/option[@selected='selected']")

            self._info(len(content_ls))
            if len(content_ls) == 0:
                field_name = r.find_element_by_xpath("./td[2]").text
                content = r.find_element_by_xpath("./td[3]").text
                
            else:
                '''if it is in dropdown list,for different type of product will have different map here'''
                
                if account_type == 'CARD':
                    continue    #TODO
                
                if account_type == 'CASA':
                    field_name = u'Account Name:'
                    content = account_name
                    
                if account_type == 'LOAN':
                    self._info("continue")
                    continue
                
                if account_type == 'DEPOSIT':
                    continue    #TODO
                
                
            self._info("content "+content)
            account_information.append([field_name.strip(),
                             content.strip().replace(' ','')])

            
        return account_information
    
    def read_ibnk_Single_accounts_txn(self,account_name):
        """Read iBanking Accounts list for comparing with Accounts in BMW.
        
        See `Read BMW Accounts`
        
        "See" list comparing.
        """
        return self._run('read_ibnk_Single_accounts_txn')
    
    def read_ibnk_Single_accounts_txn_in(self,account_name):

       
        account_txn_list = []

        ''' Return a list of all accounts information, cards and loans from iBanking.
        '''
        self.click_element("//div[@id='parentMenuHeadLink']/a/table/tbody/tr/td")

        self.wait_until_page_contains("Account")


        self.click_link(account_name)
        
        self.wait_until_page_contains("Transaction History")

        self.wait_until_page_contains_element("//table[@id='vAcctTrxnList']")

        self.click_link("Show Filters")

        self.input_text("//input[@id='searchHistoryVO.startDate']","04/04/2012")

        self.click_element("//tr[@id='ShowFilter']/td/span")

        time.sleep(10)

        
        account_txn = self._element_find("//table[@id='vAcctTrxnList']/tbody/tr[@class='odd' or @class='even']", False, False)

        self._info(len(account_txn))
        
        for r in account_txn:  # TODO

            content = r.find_element_by_xpath("./td[2]")
            currency = r.find_element_by_xpath("./td[3]")
            amount = r.find_element_by_xpath("./td[5]")
            if (amount.text).strip()=='':
                amount = r.find_element_by_xpath("./td[4]")
                
            self._info("content "+content.text)
            self._info("amount "+amount.text)

            content_t=(content.text).strip()
            amount_t = (currency.text).strip()+(amount.text).strip()
            account_txn_list.append([content_t,
                             amount_t])

        return account_txn_list

    def read_bmw_accounts_information(self):
        """Read iBanking Accounts list for comparing with Accounts in BMW.
        
        See `Read BMW Accounts`
        
        "See" list comparing.
        """
        return self._run('read_bmw_accounts_information')
    
    def _read_bmw_accounts_information_in(self):

        ''' Return a list of all accounts information, cards and loans from bmw.
        '''
        account_ls =self._
        _accounts_in()
        
        account_information = []
        account_info_all = []
        
        for i in xrange(len(account_ls)):

            self._info(account_ls[i][0]) 
            account_information = self.read_bmw_Single_accounts_information_in(account_ls[i][0])
            account_info_all.append(account_information)
            self.click_link("Go Back")
            self.wait_until_page_contains("List View")
            self._info("Go Back once")
            self.wait_until_page_contains("Go Back")
            self.click_link("Go Back")
            self._info("Go Back twice")
            self.wait_until_page_not_contains("Loading")
            
            
        return account_info_all
    
    def _read_bmw_accounts_information_id(self):

        ''' Return a list of all accounts information, cards and loans from bmw.
        '''
        account_ls =self._read_bmw_accounts_id()
        
        account_information = []
        account_info_all = []
        
        for i in xrange(len(account_ls)):

            self._info(account_ls[i][0]) 
            account_information = self.read_bmw_Single_accounts_information_in(account_ls[i][0])
            account_info_all.append(account_information)
            self.click_link("Go Back")
            self.wait_until_page_contains("List View")
            self._info("Go Back once")
            self.wait_until_page_contains("Go Back")
            self.click_link("Go Back")
            self._info("Go Back twice")
            self.wait_until_page_not_contains("Loading")
            
            
        return account_info_all

    def read_bmw_Single_accounts_information_in(self,account_number):

        ''' Return a list of give accounts information, cards and loans from bmw.

            param: account_number
            
        '''
    
        account_information = []
        
        ''' if account type is not in I have,then page need scroll down'''
        
        if len(account_number)!= 11:

            self.execute_javascript('window.scrollTo(0,200)')

        time.sleep(2)
        ''' click account which required'''
        self.click_element("//a[contains(p[2],"+"'"+account_number+"')]")

        self.wait_until_page_not_contains("Loading")
        
        ''' check if will show alert message like no transactions'''
        alert = self._element_find("//div[@class='lightbox']", False, False)
        
        ''' for if have alert message then click ok '''
        if len(alert) != 0:
            self._info("have alert")
            self.click_element("id=button-1")
                
        else:
            self._info("do not have alert")
                
        self.click_link("info")

        self.wait_until_page_not_contains("Loading")

        self.wait_until_page_contains_element("//div[@class='ember-view']/table/tbody/tr")
            
        account_info = self._element_find("//div[@class='ember-view']/table/tbody/tr", False, False)

        self._info(len(account_info))

        ''' store the lable and content for account information'''
        for r in account_info:  # TODO

            field_name = r.find_element_by_xpath(".//td[1]")

            #self._info("field_name "+field_name.text)
            
            content = r.find_element_by_xpath(".//td[2]")
                
            #self._info("content "+content.text)
                
            account_information.append([field_name.text,
                            content.text.replace(' ','')])
            
        return account_information

    def read_bmw_Single_accounts_txn_in(self,account_name):

        ''' Return a list of give accounts information, cards and loans from bmw.
        '''
    
        account_txn_list = []

        self.click_element("//a[contains(p,"+"'"+account_name+"')]")

        self.wait_until_page_not_contains("Loading")
            
        account_txn = self._element_find("//div[@id='holder-template']/div/div/div/table[2]/tbody/tr", False, False)

        self._info(len(account_txn))
        
        for r in account_txn:  # TODO

            content = r.find_element_by_xpath("./td[1]/a/p")

            self._info("content "+content.text)
            
            amount = r.find_element_by_xpath("./td[2]/a")
                
            self._info("amount "+amount.text)
                
            account_txn_list.append([content.text,
                            amount.text])
            
        return account_txn_list

